package com.topvision.myviewtest.rxjava.rxtest;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

import java.io.File;

/**
 * Author: lucy
 * Comment: //TODO
 * Date: 2017-09-28 14:08
 */

public class BitmapUtils {
    public static Bitmap decodeSampledBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {

        // 第一次加载时 将inJustDecodeBounds设置为true 表示不真正加载图片到内存
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        // 根据目标宽和高 以及当前图片的大小 计算出压缩比率
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // 将inJustDecodeBounds设置为false 真正加载图片 然后根据压缩比率压缩图片 再去解码
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    //计算压缩比率 android官方提供的算法
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            //将当前宽和高 分别减小一半
            final int halfHeight = height / 2;
            final int halfWidth = width / 2;

            // Calculate the largest inSampleSize value that is a power of 2 and keeps both
            // height and width larger than the requested height and width.
            while ((halfHeight / inSampleSize) > reqHeight
                    && (halfWidth / inSampleSize) > reqWidth) {
                inSampleSize *= 2;
            }
        }
        return inSampleSize;
    }

    public static Bitmap getBitmap(Context context, int res, int radius) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = radius;//直接设置它的压缩率
        Bitmap b = null;
        try {
            b = BitmapFactory.decodeResource(context.getResources(), res, options);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return b;
    }

    public static Bitmap getBitmap(File file, int radius) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = radius;//直接设置它的压缩率
        Bitmap b = null;
        try {
            b = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return b;
    }

    public static Bitmap getBitmap(Bitmap bitmap, float radius) {
        Matrix matrix = new Matrix();
        matrix.setScale(radius, radius);
        Bitmap bm = null;
        bm = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                bitmap.getHeight(), matrix, true);
        return bm;
    }
}
